#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from datetime import datetime
import calendar
import sys

reload(sys)
sys.setdefaultencoding("utf-8")


def json_convert():
    # data = abc.get("BODY")
    # if data is not None:
    #     del abc["BODY"]

    res = {}
    # 取出原json其他数据并放到返回结果中
    # for k in abc:
    #     res[k] = abc[k]
    #
    # # 如果data为空返回空json
    # if data is None:
    #     res["data"] = {}
    #     return json.dumps(res, ensure_ascii=False)

    data = BODY
    data = data.get("ENT_INFO")

    newData = data.copy()

    # 企业照面信息
    bl_map = {"ENTNAME": "enterpriseName", "CREDITCODE": "creditCode", "ORGCODES": "orgCode", "FRNAME": "frName",
              "REGNO": "regNo", "ESDATE": "esDate", "ENTTYPE": "enterpriseType", "ENTSTATUS": "enterpriseStatus",
              "INDUSTRYCOCDE": "industryCode", "OPFROM": "openFrom", "OPTO": "openTo", "REGCAP": "regCap",
              "ZSOPSCOPE": "operateScope", "DOM": "address", "REGCAPCUR": "regCapCur", "INDUSTRYCONAME": "industryName",
              "REGORG": "regOrg", "APPRDATE": "apprDate"}
    basic_list = get_json_obj(data.get("BASIC"))
    del newData["BASIC"]
    newData["basicList"] = change_json_key([basic_list], bl_map)

    # 企业股东及出资信息
    shl_map = {"SHANAME": "shareholderName", "SUBCONAM": "subConam", "FUNDEDRATIO": "fundedRatio",
               "REGCAPCUR": "regCapCur", "COUNTRY": "country", "CONDATE": "conDate"}
    share_holder_list = get_json_array(data.get("SHAREHOLDER"))
    del newData["SHAREHOLDER"]
    newData["shareHolderList"] = change_json_key(share_holder_list, shl_map)

    # 企业历史变更信息
    al_map = {"ALTDATE": "altDate", "ALTITEM": "altItem", "ALTBE": "altBe", "ALTAF": "altAf"}
    alter_list = get_json_array(data.get("ALTER"))
    del newData["ALTER"]
    newData["alterList"] = change_json_key(alter_list, al_map)

    # 股权冻结历史信息
    sfl_map = {"FROFROM": "froFrom", "FROTO": "froTo", "FREEZE_DATE": "thawDate"}
    shares_frost_ist = get_json_array(data.get("JUDICIALAIDDETAIL"))
    del newData["JUDICIALAIDDETAIL"]
    newData["sharesFrostList"] = change_json_key(shares_frost_ist, sfl_map)

    # 行政处罚
    cil_map = {"PUBLICDATE": "publicDate", "PENDECNO": "penDecNo", "PENAUTH_CN": "penAuth", "ILLEGACTTYPE": "illegFact"}
    case_info_list = get_json_array(data.get("ENTCASEBASEINFO"))
    del newData["ENTCASEBASEINFO"]
    newData["caseInfoList"] = change_json_key(case_info_list, cil_map)

    # 股权出质信息
    spl_map = {"STK_PAWN_REGDATE": "stkPawnRegDate", "STK_PAWN_STATUS": "stkPawnStatus",
               "STK_PAWN_CZAMT": "stkPawnCzAmount"}
    stock_pawn_list = get_json_array(data.get("STOCKPAWN"))
    del newData["STOCKPAWN"]
    newData["stockPawnList"] = change_json_key(stock_pawn_list, spl_map)

    # 动产抵押-抵押人信息
    mpl_map = {"MAB_REGNO": "mabRegNo", "MAB_PER_NAME": "mabPerName"}
    mortgage_per_list = get_json_array(data.get("MORTGAGEPER"))
    del newData["MORTGAGEPER"]
    newData["mortgagePerList"] = change_json_key(mortgage_per_list, mpl_map)

    # 动产抵押-基本信息
    mbl_map = {"MAB_REGNO": "mabRegNo", "MAB_REG_DATE": "mabRegDate", "MAB_STATUS": "mabStatus",
               "MAB_GUAR_AMT": "mabGuarAmount"}
    mortgage_basic_list = get_json_array(data.get("MORTGAGEBASIC"))
    del newData["MORTGAGEBASIC"]
    newData["mortgageBasicList"] = change_json_key(mortgage_basic_list, mbl_map)

    # 企业对外投资信息
    eil_map = {"ENTJGNAME": "entName", "ENTSTATUS": "entStatus", "REGCAP": "regCap", "REGNO": "regNo"}
    entinv_item_list = get_json_array(data.get("ENTINV"))
    del newData["ENTINV"]
    newData["entinvItemList"] = change_json_key(entinv_item_list, eil_map)

    # 法定代表人对外投资信息
    fl_map = {"ENTNAME": "entName", "ENTSTATUS": "entStatus", "NAME": "frName", "REGNO": "regNo"}
    frinv_list = get_json_array(data.get("FRINV"))
    del newData["FRINV"]
    newData["frinvList"] = change_json_key(frinv_list, fl_map)

    # 法定代表人在其他企业任职信息
    frpl_map = {"ENTNAME": "entName", "ENTSTATUS": "entStatus"}
    fr_position_list = get_json_array(data.get("FRPOSITION"))
    del newData["FRPOSITION"]
    newData["frPositionList"] = change_json_key(fr_position_list, frpl_map)

    # 分支机构信息
    fl_map = {"BRNAME": "brName"}
    filiation_list = get_json_array(data.get("FILIATION"))
    del newData["FILIATION"]
    newData["filiationList"] = change_json_key(filiation_list, fl_map)

    # 清算信息
    ll_map = {"LIGPRINCIPAL":"ligprincipal"}
    liquidation_list = get_json_array(data.get("LIQUIDATION"))
    del newData["LIQUIDATION"]
    newData["liquidationList"] = change_json_key(liquidation_list, ll_map)

    # 企业主要管理人员
    pl_map = {"PERNAME":"name","POSITION":"position"}
    person_list = get_json_array(data.get("PERSON"))
    del newData["PERSON"]
    newData["personList"] = change_json_key(person_list, pl_map)

    res["data"] = {"R1103V3": [newData]}
    return json.dumps(res, ensure_ascii=False)


def isfloat(x):
    try:
        if isinstance(float(x), float):
            if str(x) in ["inf", "infinity", "INF", "INFINITY", "True"]:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def change_json_key(json_arr, json_map):
    """
    替换掉json数组中的所有需要替换的字段
    :param json_arr: 需要替换的json
    :param json_map: 替换的映射json，key为原字段，value为替换后的字段
    :return:
    """
    for obj in json_arr:
        items = json_map.items()
        for k, v in items:
            try:
                value = obj.get(k)
                if value is not None:
                    obj[v] = value
                    del obj[k]
                else:
                    obj[v] = obj.get(v)
            except:
                continue
    return json_arr


def get_json_array(json_arr):
    try:
        return json_arr if isinstance(json_arr, list) else []
    except:
        return []


def get_json_obj(json_obj):
    try:
        return json_obj if isinstance(json_obj, dict) else {}
    except:
        return {}


if __name__ == "__main__":
    file_obj = open(r"../data/EG_DSJ.json", "r")
    content = file_obj.read()
    abc = json.loads(content, strict=False)
    aa = json_convert()
    print aa

result = json_convert()
